package com.cnbm.wcsbasic.protocol.netty.io.common;



import com.cnbm.wcsbasic.protocol.netty.io.common.byteutils.ByteUtils;
import com.cnbm.wcsbasic.protocol.netty.io.common.enmuc.PlcVarType;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.UUID;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2022/10/24 16:27
 */
public class Utils {
    /**
     * java生成随机数字15位数
     * @return
     */
    public static String getTransationId() {
        String val = String.valueOf(System.currentTimeMillis());
        Random random = new Random();
        for (int i = 0; i < 2; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }

    /**
     * 获取指定长度的随机数
     * (获取指定长度uuid)
     *
     * @return
     */
    public static String getUUID(int len)
    {
        if(0 >= len)
        {
            return null;
        }

        String uuid = getUUID();
        StringBuffer str = new StringBuffer();

        for (int i = 0; i < len; i++)
        {
            str.append(uuid.charAt(i));
        }

        return str.toString();
    }

    /**
     *32位默认长度的uuid
     * (获取32位uuid)
     *
     * @return
     */
    public static  String getUUID()
    {
        return UUID.randomUUID().toString().replace("-", "");
    }


    public static byte[] getBytesNum(PlcVarType plcVarType, Integer length, Integer strSize){

        byte[] remainders = null;
        if(plcVarType.isArray()){
            Integer readSize = plcVarType.getDataSize() * length;
            if(plcVarType.getName().equals("BOOL")){
                //特殊处理
                return ByteUtils.remainderForBool(readSize);
            }else if(plcVarType.getName().equals("STRING")){
                 return ByteUtils.remainders((strSize+2)*length);
            }
            remainders = ByteUtils.remainders(readSize);
        }else {
            if(plcVarType.getName().equals("BOOL")){
                return ByteUtils.remainderForBool(1);
            }else if(plcVarType.getName().equals("STRING")){
                return ByteUtils.remainders(strSize+2);
            }
            remainders = ByteUtils.remainders(plcVarType.getDataSize());
        }
        return remainders;
    }


    /*
        type:
            1.返回的是这种格式：2021-08-16 15:00:05
            2.返回的是这种格式：20210816150021
     */
    public static String getNowDate(Integer type){
        if(type==1){
            return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }else {
            return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        }
    }
}
